package com.controller;



import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.common.constant.SysFileConstant;
import com.utils.RandomStringGenerator;
import com.utils.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;


@Slf4j
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class SysFileController {

    private final SysFileConstant sysFileConstant;


    @PostMapping("/upload")
    public Result uploadToPath(@RequestParam("file") MultipartFile file, String savePath, HttpServletRequest request) throws Exception {
        if(ObjectUtils.isNull(file)) {
            throw new Exception("未找到上传文件!");
        }


        if(!StringUtils.hasText(savePath) || "".equals(savePath.trim())) {
            savePath = sysFileConstant.SAVE_PATH;
        }
        String fileName = RandomStringGenerator.generateRandomString(6) + file.getOriginalFilename();

        //创建存放目录
        File saveFiles = new File(savePath);
        if(!saveFiles.exists()){
            saveFiles.mkdirs();//创建文件夹,如果上级目录不存在，则挨个创建目录
        }
        //指定需要保存的文件名称和路径
        String filePath = savePath + "/" + fileName;
        File saveFile = new File(filePath);
        try {
            file.transferTo(saveFile);//保存文件到指定目录
            //FileUtil.writeBytes(file.getBytes(), saveFile);

        } catch (Exception e) {
            log.error("文件保存到临时目录失败!" + e.getMessage());
        }
        StringBuffer requestURL = request.getRequestURL();
        String substring = requestURL.substring(0, requestURL.indexOf("/file"));
        String filePathResult = substring + SysFileConstant.PREFIX_URL + filePath;
        return Result.success().setData(filePathResult);
    }

}
